package uk.ac.cam.djjb2.mygame;

import java.io.DataInput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

public abstract class NetManager {
	private class Message {
		public final int senderId;
		public final DataInput message;
		
		public Message(int senderId, DataInput message) {
			this.senderId = senderId;
			this.message = message;
		}
	}
	private ConcurrentLinkedQueue<Message> messageQueue = new ConcurrentLinkedQueue<Message>();
	
	private Map<Integer, MessageReceiver> messageReceivers = new HashMap<Integer, MessageReceiver>();
	
	public void addMessageReceiver(int messageId, MessageReceiver messageReceiver) {
		messageReceivers.put(messageId, messageReceiver);
	}
	public MessageReceiver removeMessageReceiver(int messageId) {
		return messageReceivers.remove(messageId);
	}
	private void receiveMessage(int senderId, DataInput message) throws IOException, InvalidMessageException {
		int id = message.readInt();
		messageReceivers.get(id).receive(senderId, id, message);
	}
	public void postMessage(int senderId, DataInput message) {
		messageQueue.add(new Message(senderId, message));
	}
	public void processMessages() throws IOException, InvalidMessageException {
		Message message;
		while ((message = messageQueue.poll()) != null) {
			receiveMessage(message.senderId, message.message);
		}
	}
}
